﻿Imports System.Runtime.Serialization
Imports System.IO


''' <summary>
''' Represents a specific file within a library
''' </summary>
''' <remarks></remarks>
<Serializable()>
Public Class RawSource
    Implements ISerializable

#Region "Serialization"
    Private Sub New(info As SerializationInfo, context As StreamingContext)
        Dim version As Integer = info.GetInt32("version")

        If version >= 1 Then
            Path = info.GetString("fileName")
            ObjectType = CType(info.GetInt32("objectType"), ObjectType)
            Library = info.GetValue(Of RawLibrary)("library")
        End If
    End Sub


    Public Sub GetObjectData(info As SerializationInfo, context As StreamingContext) Implements ISerializable.GetObjectData
        info.AddValue("version", 1)

        'Version 1 data
        info.AddValue("fileName", Path)
        info.AddValue("objectType", ObjectType)
        info.AddValue("library", Library)
    End Sub
#End Region

    Public Property Path As String
    Public Property ObjectType As ObjectType
    Public Property Library As RawLibrary

    Public Sub New(filename As String, library As RawLibrary, objectType As ObjectType)
        Me.Path = filename
        Me.Library = library
        Me.ObjectType = objectType
    End Sub

    Public Function GetObjects() As IEnumerable(Of RawObject)
        Return Library.GetObjectsInSource(Me)
    End Function


    Public Sub WriteToStream(ByVal writer As StreamWriter, ByVal RawLibrary As RawLibrary, options As ExportOptions)
        writer.WriteLine(IO.Path.GetFileNameWithoutExtension(Path))
        writer.WriteLine()
        writer.Write(String.Format("[OBJECT:{0}]", ObjectType))

        Dim data As IEnumerable(Of RawObject) = RawLibrary.GetObjectsInSource(Me)
        If options.SortObjects Then
            data = data.OrderBy(Of String)(Function(x) x.objectId)
        End If

        For Each obj As RawObject In data
            writer.WriteLine() 'terminate the previous line
            writer.WriteLine() 'add a blank line

            obj.WriteToStream(writer)
        Next

        'Do BODYGLOSS entries if any exist for this source
        If ObjectType = ObjectType.BODY Then
            Dim gloss As New List(Of BodyGlossEntry)(From g As BodyGlossEntry In Library.BodyGlossary Where g.Source Is Me)
            If gloss.Count > 0 Then
                writer.WriteLine() 'terminate the previous line
                writer.WriteLine() 'add a blank line

                For Each entry As BodyGlossEntry In gloss
                    writer.WriteLine(entry.GlossToken.ToString)
                Next
            End If
        End If
    End Sub
End Class
